package com.ljy.my_study.util;

import com.ljy.my_study.leetcode.对称二叉树.TestMain.TreeNode;

/**
 * @author James
 * @date 2018年9月29日
 */
public class TreeNodeUtil {

    public static TreeNode deserialize(String data) {
        if (data == null || data.isEmpty()) {
            return null;
        }
        String[] arrStr = data.split(",");
        TreeNode root = null;
        TreeNode[] treeNodeArr = new TreeNode[arrStr.length];
        for (int i = 0; i < arrStr.length; i++) {
            if (!arrStr[i].equals("#") && !arrStr[i].equals("null")) {
                Integer intVal = Integer.valueOf(arrStr[i]);
                TreeNode thisNode = new TreeNode(intVal);
                if (i == 0) {
                    root = thisNode;
                }
                treeNodeArr[i] = thisNode;
                if (i % 2 == 0) {
                    if (i / 2 - 1 >= 0) {
                        if (treeNodeArr[i / 2 - 1] != null) {
                            treeNodeArr[i / 2 - 1].right = thisNode;
                        }
                    }
                } else {
                    if ((i + 1) / 2 - 1 >= 0) {
                        if (treeNodeArr[(i + 1) / 2 - 1] != null) {
                            treeNodeArr[(i + 1) / 2 - 1].left = thisNode;
                        }
                    }
                }
            }
        }
        return root;
    }


    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }

        @Override
        public String toString() {
            return "{\"val\":\"" + val + "\"} ";
        }

    }
}
